import React, {Component} from 'react'
import {View, Text, Image, TouchableHighlight, Dimensions} from 'react-native'
import Attachment from './attachment'

var {height, width} = Dimensions.get('window')
//把props.attachments里面按照类型分别渲染不同的组件
class AttachmentManager extends Component {
    static defaultProps = {
        attachments: []
    }

    constructor (props) {
        super(props)
        this.state = {
            attachments: props.attachments,
            image_index: 0
        }
    }

    add_image_index = () => {
        this.setState({image_index: this.state.image_index + 1})
    }


    componentWillReceiveProps(nextProps) {
        this.setState({attachments: nextProps.attachments})
    }

    render () {
        const image_attachments = this.state.attachments.filter((attachment) => {return attachment.type == "image"})
        const urls = image_attachments.map((attachment) => {
            if (attachment.url.match(/^https:\/\/*/)) {
                return {url: attachment.url}
            } else {
                return {url: App.host + '/api' + attachment.url}
            }
        })
        let image_index = -1
         return(
            <View style={{flex: 1, flexWrap: 'wrap', flexDirection: 'row', alignItems: 'flex-start'}}>
                {
                    this.state.attachments.map((attachment, index) => {
                        if (attachment.type == 'image') {image_index += 1}
                        return (
                            <Attachment
                                key={index}
                                urls={urls}
                                index={image_index}
                                navigation={this.props.navigation}
                                attachment={attachment}
                                style={{width: width / 6, margin: 12}}
                            />
                        )
                    })
                }
            </View>

         )
        
    }
}

export default AttachmentManager